package com.group.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.group.domain.Comment;
import com.group.domain.Media;
import com.group.domain.User;
import com.group.utils.HibernateUtil;

/**
 * 评论数据表操作
 * 
 * @author 86191
 *
 */
public class CommentDao {
	
	/**
	 * 获取评论总数
	 * 
	 * @return						评论总数
	 */
	public long count() {
		Session session = HibernateUtil.openSession();
		long count = 0;
		try {
			count = (long) session.createQuery("SELECT COUNT(*) FROM Comment WHERE isDelete = false").uniqueResult();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("Error");
		} finally {
			session.close();
		}
		return count;
	}
	
	/**
	 * 统计指定用户的评论数量
	 * 
	 * @param user	指定用户
	 * @return			该用户的评论数量
	 */
	public long countByUser(User user) {
		Session session = HibernateUtil.openSession();
		long count = 0;
		try {
			Criteria criteria = session.createCriteria(Comment.class);
			criteria.add(Restrictions.eq("user", user));
			criteria.add(Restrictions.eq("isDelete", false));
			count = criteria.list().size();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("Error");
		} finally {
			session.close();
		}
		return count;
	}
	
	/**
	 * 通过id获取评论
	 * @param id 评论id
	 * @return		id为指定id的评论
	 */
	public Comment findOneById(int id) {
		Session session = HibernateUtil.openSession();
		try {
			Comment comment = null;
			comment = (Comment) session.get(Comment.class, id);
			return comment;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}
	
	/**
	 * 分页查询评论列表
	 * 
	 * @param pageNo 页码
	 * @param pageSize 每页的个数
	 * @return  指定页码下的用户列表
	 */
	public List<Comment> findCommentListByPage(int pageNo, int pageSize,User user){
		Session session = HibernateUtil.openSession();
		List<Comment> comments = null;
		try {
			Criteria criteria = session.createCriteria(Comment.class);
            // 设置排序条件
            criteria.addOrder(Order.desc("commentDate"));
            // 筛选出已登陆用户的评论
            criteria.add(Restrictions.eq("user", user));
            criteria.add(Restrictions.eq("isDelete", false));
            // 设置分页信息
            criteria.setFirstResult((pageNo - 1) * pageSize);
            criteria.setMaxResults(pageSize);
            // 获取用户列表
            comments = criteria.list();
			return comments;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}
	
	/**
	 * 查询用户评论列表
	 * @param user 指定用户
	 * @return  指定用户的所有评论
	 */
	public List<Comment> findCommentListByUser(User user){
		Session session = HibernateUtil.openSession();
		List<Comment> comments = null;
		try {
			Criteria criteria = session.createCriteria(Comment.class);
            // 设置排序条件
            criteria.addOrder(Order.desc("id"));
            // 筛选出已登陆用户的评论
            criteria.add(Restrictions.eq("user", user));
            criteria.add(Restrictions.eq("isDelete", false));
            // 获取用户列表
            comments = criteria.list();
			return comments;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}
	
	/**
	 * 分页查询评论列表
	 * 
	 * @param pageNo 页码
	 * @param pageSize	每页的个数
	 * @param media	书/影/音
	 * @return  指定页码下的用户列表
	 */
	public List<Comment> findCommentListByPage(int pageNo, int pageSize,Media media){
		Session session = HibernateUtil.openSession();
		List<Comment> comments = null;
		try {
			Criteria criteria = session.createCriteria(Comment.class);
            // 设置排序条件
            criteria.addOrder(Order.desc("commentDate"));
            // 筛选出已登陆用户的评论
            criteria.add(Restrictions.eq("media", media));
            criteria.add(Restrictions.eq("isDelete", false));
            // 设置分页信息
            criteria.setFirstResult((pageNo - 1) * pageSize);
            criteria.setMaxResults(pageSize);
            // 获取用户列表
            comments = criteria.list();
			return comments;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}
	/**
	 * 查询指定media的评论列表
	 * @param media	指定media
	 * @return				该media的评论列表
	 */
	public List<Comment> findCommentListByMedia(Media media){
		Session session = HibernateUtil.openSession();
		List<Comment> comments = null;
		try {
			Criteria criteria = session.createCriteria(Comment.class);
            // 设置排序条件
            criteria.addOrder(Order.desc("commentDate"));
            // 筛选出已登陆用户的评论
            criteria.add(Restrictions.eq("media", media));
            criteria.add(Restrictions.eq("isDelete", false));
            // 获取用户列表
            comments = criteria.list();
			return comments;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}
	
	/**
	 * 分页查询评论列表
	 * @param pageNo 页码
	 * @param pageSize 每页评论的个数
	 * @return  指定页码下的用户列表
	 */
	public List<Comment> findCommentListByPage(int pageNo, int pageSize){
		Session session = HibernateUtil.openSession();
		List<Comment> comments = null;
		try {
			Criteria criteria = session.createCriteria(Comment.class);
			criteria.add(Restrictions.eq("isDelete", false));
            // 设置排序条件
            criteria.addOrder(Order.asc("id"));
            // 设置分页信息
            criteria.setFirstResult((pageNo - 1) * pageSize);
            criteria.setMaxResults(pageSize);
            // 获取用户列表
            comments = criteria.list();
			return comments;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}
	
	
	/**
	 * 保存评论
	 * 
	 * @param comment	评论
	 * @return	是否保存成功
	 */
	public boolean saveComment(Comment comment) {
		Session session = HibernateUtil.openSession();
		Transaction transaction = null;
		int result = 0;
		try {
			transaction = session.beginTransaction();
			// 保存评论
			result = (Integer) session.save(comment);
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
		} finally {
			session.close();
		}
		// 计算并保存平均评分
		averageRating(comment.getMedia());
		return result > 0;
	}
	
	/**
	 * 计算并保存指定media的平均评分
	 * @param	media	指定media
	 */
	public void averageRating(Media media) {
		Session session = HibernateUtil.openSession();
		Double averageRating;
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Criteria criteria = session.createCriteria(Comment.class).setProjection(Projections.avg("rating"))
					.add(Restrictions.eq("media", media)).add(Restrictions.eq("isDelete", false));
			averageRating = (Double) criteria.uniqueResult();
			media.setAverageRating(averageRating);
			session.update(media);
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
		} finally {
			// TODO: handle finally clause
			session.close();
		}
	}
	
	
	/**
	 * 编辑评论内容
	 * 
	 * @param comment				修改后的评论内容
	 * @return						是否修改成功
	 */
	public boolean update(Comment comment) {
		Session session = HibernateUtil.openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			session.update(comment);
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
		} finally {
			session.close();
		}
		averageRating(comment.getMedia());
		return true;
	}
	
	/**
	 * 删除评论
	 * 
	 * 	@param id					要删除评论的id
	 * @return						是否删除成功
	 */
	public boolean delete(int id) {
		Session session = HibernateUtil.openSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Comment comment = session.get(Comment.class, id);
			comment.setIsDelete(true);
			session.update(comment);
			averageRating(comment.getMedia());
			transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
			return false;
		} finally {
			session.close();
		}
		return true;
	}
	
}
